
package com.directthought.elasticweb;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.IOException;
import java.io.OutputStream;
import java.net.Socket;
import java.net.ServerSocket;
import java.net.UnknownHostException;

import org.apache.log4j.Logger;

/**
 * This class listens on a port, accepts connection and simply writes a 0 byte back.
 */
public class HCListener extends Thread {
	private static Logger logger = Logger.getLogger(HCListener.class);
	public static final int HC_SOCKET = 2010;

	public HCListener() { }

	public void run() {
		while (true) {
			try {
				ServerSocket ss = new ServerSocket(HC_SOCKET);
				while (true) {
					Socket sock = ss.accept();
					InputStream iStr = sock.getInputStream();
					String hostToCheck = new BufferedReader(new InputStreamReader(iStr)).readLine();
					logger.debug("asked to ping host : "+hostToCheck);
					// ping that host, and reply
					boolean hostOK = PingListener.pingHost(hostToCheck);
					logger.debug("host alive : "+hostOK);
					OutputStream oStr = sock.getOutputStream();
					oStr.write(hostOK?1:0);
					oStr.flush();
					sock.close();
				}
			} catch (Exception ex) {
				logger.error("problem accepting connection. will keep going.", ex);
			}
		}
	}

	static boolean requestCheck(String hostName, String hostToCheck) {
		boolean hostOK = false;
		try {
			logger.debug("asking "+hostName+" to ping host : "+hostToCheck);
			Socket sock = new Socket(hostName, HC_SOCKET);
			OutputStream oStr = sock.getOutputStream();
			oStr.write((hostToCheck+"\n").getBytes());
			InputStream iStr = sock.getInputStream();
			int val = iStr.read();
			if (val != -1) {
				hostOK = (val==1);
			}
			logger.debug("got reply, hostOK = "+hostOK);
			// else, can't ping
		} catch (UnknownHostException ex) {
			// can't ping
		} catch (IOException ex) {
			// can't ping
		}
		return hostOK;
	}
}
